package com.egao.common.module.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egao.common.core.exception.BusinessException;
import com.egao.common.core.web.PageParam;
import com.egao.common.module.system.entity.Role;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.entity.UserRole;
import com.egao.common.module.system.mapper.TeacherMapper;
import com.egao.common.module.system.mapper.UserRoleMapper;
import com.egao.common.module.system.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 校用户管理接口实现类
 * @author pyx
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, User> implements TeacherService {
    @Autowired(required = false)
    private UserRoleMapper userRoleMapper;

    @Override
    public List<User> listPage(PageParam<User> page) {
        List<User> teachers = baseMapper.listPage(page);
        //查询角色
        selectUserRoles(teachers);
        return teachers;
    }

    @Override
    public List<User> listAll(Map<String, Object> page) {
        List<User> teachers = baseMapper.listAll(page);
        // 查询用户的角色
        selectUserRoles(teachers);
        return teachers;
    }

    @Override
    public boolean saveUser(User teacher) {
        if (teacher.getUsername() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("username", teacher.getUsername())) > 0) {
            throw new BusinessException("账号已存在");
        }
        if (teacher.getEmail() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("email", teacher.getEmail())) > 0) {
            throw new BusinessException("邮箱已存在");
        }
        boolean result = baseMapper.insert(teacher) > 0;
        if (result) {
            addUserRoles(teacher.getUserId(), teacher.getRoleIds(), false);
        }
        return result;
    }

    @Override
    public boolean updateUser(User teacher) {
        if (teacher.getUsername() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("username", teacher.getUsername()).ne("user_id", teacher.getUserId())) > 0) {
            throw new BusinessException("账号已存在");
        }
        if (teacher.getEmail() != null && baseMapper.selectCount(new QueryWrapper<User>()
                .eq("email", teacher.getEmail()).ne("user_id", teacher.getUserId())) > 0) {
            throw new BusinessException("邮箱已存在");
        }
        boolean result = baseMapper.updateById(teacher) > 0;
        if (result) {
            addUserRoles(teacher.getUserId(), teacher.getRoleIds(), true);
        }
        return result;
    }

    private void selectUserRoles(List<User> users) {
        if (users != null && users.size() > 0) {
            List<Integer> userIds = users.stream().map(User::getUserId).collect(Collectors.toList());
            List<Role> userRoles = userRoleMapper.listByUserIds(userIds);
            for (User user : users) {
                List<Role> roles = userRoles.stream().filter(d -> user.getUserId().equals(d.getUserId())).collect(Collectors.toList());
                user.setRoles(roles);
            }
        }
    }

    /**
     * 添加用户角色
     */
    private void addUserRoles(Integer userId, List<Integer> roleIds, boolean deleteOld) {
        if (deleteOld) {
            userRoleMapper.delete(new UpdateWrapper<UserRole>().eq("user_id", userId));
        }
        if (userRoleMapper.insertBatch(userId, roleIds) < roleIds.size()) {
            throw new BusinessException("操作失败");
        }
    }
}
